import 'dart:math';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:provider_flutter/model/cart_model.dart';

class CatalogPage extends StatefulWidget {
  const CatalogPage({Key? key}) : super(key: key);

  @override
  State<CatalogPage> createState() => _CatalogPageState();
}

class _CatalogPageState extends State<CatalogPage> {
  List<Product> _list = <Product>[];
  @override
  void initState() {
    super.initState();
    for (var i = 0; i < 20; i++) {
      _list.add(
          Product(id: i, name: 'product->${i}', price: double.parse('${i}')));
    }
  }

  @override
  Widget build(BuildContext context) {
    CartModel cartModel = context.watch<CartModel>();
    return Scaffold(
      appBar: AppBar(
        title: const Text('商品列表'),
        actions: [
          IconButton(
              onPressed: () {
                Navigator.of(context).pushNamed('/cart');
              },
              icon: Icon(Icons.shopping_cart))
        ],
      ),
      body: ListView.builder(
          itemCount: _list.length,
          itemBuilder: (context, index) {
            bool isInCart =
                cartModel.cart.any((element) => element == _list[index]);
            return ListTile(
              leading: Image.network(
                'http://www.tangguoketang.com/img/banner01.7c3681ef.png',
                width: 100,
              ),
              title: Text('${_list[index].name}'),
              trailing: isInCart
                  ? Icon(Icons.check)
                  : IconButton(
                      icon: Icon(Icons.add),
                      onPressed: () {
                        cartModel.add(_list[index]);
                      },
                    ),
            );
          }),
      floatingActionButton: FloatingActionButton(
        child: Text('${cartModel.cart.length}'),
        onPressed: () {
          cartModel.removeAll();
        },
      ),
    );
  }
}

class Product {
  int? id;
  String? name;
  double? price;

  Product({this.id, this.name, this.price});
}
